import React, { Component } from 'react'
import { Text, View, Animated, StyleSheet, Button, TouchableOpacity, TextInput } from 'react-native'
import { linear } from 'react-native/Libraries/Animated/Easing'
import Video from 'react-native-video'
import Entypo from 'react-native-vector-icons/Entypo'
import AntDesign from 'react-native-vector-icons/AntDesign'
import Slider from '@react-native-community/slider'
let dataUrl = "http://www.khino.cn:8080/comment/api/song/getAll"
let mp3Url = "http://www.sanren.vip:5000/Music/"
export default class MusicPlayer extends Component {

  state = { paused: true, musics: [], musicIndex: 0, duration: 0.0, currentTime: 0.0, rotate: new Animated.Value(0), isCollection: false }

  //用来做旋转动画的变量
  rotateValue = 0
  componentDidMount() {
    fetch(dataUrl).then(resp => resp.json())
      .then(musics => { this.setState({ musics }) })

    //给rotate设置数值监听器，用于动画循环
    this.state.rotate.addListener(({ value }) => this.rotateValue = value)
    this.props.navigation.addListener('focus', () => {
      let currentMusic = this.props.route.params?.music
      let index = 0
      console.log(currentMusic)
      if (currentMusic) {
        //这个查询位置没解决
        for(var i in this.state.musics){
          if( this.state.musics[i].songId == currentMusic.songId){
            index = i
          }
        }
        // index = this.state.musics.indexOf(currentMusic)
      }
      console.log(index)
      this.setState({ musicIndex: index })
      console.log(this.state.musics)
    })
  }

  //格式化时间
  formatMediaTime(duration) {
    let min = Math.floor(duration / 60);
    let second = parseInt(duration - min * 60);
    min = min >= 10 ? min : "0" + min;
    second = second >= 10 ? second : "0" + second;
    return min + ":" + second;
  }

  //播放暂停的切换，设置动画的旋转
  _play = () => {
    let animatedFunction = Animated.loop(Animated.timing(this.state.rotate,
      { duration: 30000, toValue: this.rotateValue + 360, easing: linear, useNativeDriver: true }))
    this.state.paused ? animatedFunction.start() : animatedFunction.stop()
    this.setState(state => ({ paused: !state.paused }))

  }

  //滑动控制进度
  _sliderChange = value => {
    this.player.seek(value)
  }


  //加载后将时长设置为进度条的最大值
  _load = ({ duration }) => {
    let m = this.state.musics[this.state.musicIndex]
    this.setState({ duration })
    let url = "http://www.khino.cn:8080/comment/api/collection/isUserCollectedSong/?"
    fetch(url + "songId=" + m.songId + "&userId=1", { method: 'GET' })
      .then(resp => resp.json())
      .then(flag => {this.setState({ isCollection: flag }) })
  }

  //收藏歌曲或者取消收藏
  _like = () => {
    let m = this.state.musics[this.state.musicIndex]
    if (this.state.isCollection) {
      //取消收藏
      console.log("表哥我来取消收藏咯");
      let url = "http://www.khino.cn:8080/comment/api/collection/delayCollectedSong/?"
      fetch(url + "songId=" + m.songId + "&userId=1", { method: 'DELETE' })
        .then(resp => resp.json())
        .then(flag => {this.setState({ isCollection: !this.state.isCollection }) })
    } else {
      //添加收藏
      console.log("表哥我来收藏咯"+m.songId);
      // let collection = { collectionSongId: m.songId, collectionUserId: "1" }
      let url = "http://www.khino.cn:8080/comment/api/collection/add/?collectionSongId="+m.songId+"&collectionUserId="+1
      fetch(url, {
        method: 'POST',
        // body: JSON.stringify(collection),
        headers: { 'Content-Type': 'application/json' }
      })
        .then(resp => resp.json())
        .then(flag => {this.setState({ isCollection: !this.state.isCollection }) })
    }
  }

  //当歌曲结束时播放下一首
  _end = () => {
    let index = ++this.state.musicIndex % music.length
    this.setState({ musicIndex: index, currentTime: 0.0 })
  }


  //播放过程中同步进度条
  _setTime = ({ currentTime }) => this.setState({ currentTime })

  _toTheNext = () => {
    let index = ++this.state.musicIndex % this.state.musics.length
    this.setState({ musicIndex: index, currentTime: 0.0 })
  }

  _toTheBehind = () => {
    if (--this.state.musicIndex === -1) {
      this.setState({ musicIndex: this.state.musics.length - 1, currentTime: 0.0 })
    } else {
      this.setState({ musicIndex: --this.state.musicIndex, currentTime: 0.0 })
    }
  }


  render() {
    let { musics: mus, musicIndex: minx } = this.state
    let style = {
      transform: [{
        rotate: this.state.rotate.interpolate({
          inputRange: [0, 360], outputRange: ['0deg', '360deg']
        })
      }]
    }
    return (
      <View style={{ flex: 1, backgroundColor: "#ffd6e7", alignItems: 'center' }}>

        <Video onEnd={this._end}
          onProgress={this._setTime}
          onLoad={this._load}
          paused={this.state.paused}
          playInBackground={false} 
          ref={ref => this.player = ref} //http://www.sanren.vip:5000/Music/Fancy%20Like.mp3
          source={{ uri: mp3Url + mus[minx]?.songName + ".mp3" }} ></Video>

        <Text>{mus[minx]?.songName}</Text>
        <Text>{mus[minx]?.songSinger}</Text>

        <View style={{ flex: 6, justifyContent: 'center', alignItems: 'center' }}>
          <Animated.Image style={[styles.disc, style]} source={{ uri: mus[minx]?.songImg }} />
        </View>

        <View style={{ height: 40, width: 40, alignSelf: 'flex-end', marginRight: 25, justifyContent: 'center', alignItems: 'center' }}>
          <TouchableOpacity onPress={this._like}>
            <AntDesign name={"hearto"} size={30} color={this.state.isCollection ? "#FF0033" : "#666666"} />
          </TouchableOpacity>
        </View>

        <View style={{ flex: 1, flexDirection: 'row' }}>
          <View style={{ flex: 2, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={styles.TimeTxt}>{this.formatMediaTime(this.state.currentTime)}</Text>
          </View>
          <View style={{ flex: 13, justifyContent: 'center', alignItems: 'center' }}>
            <Slider style={{ width: 300 }} minimumTrackTintColor='white' thumbTintColor="white" maximumTrackTintColor="gray" maximumValue={this.state.duration} maximumTrackTintColor='red' value={this.state.currentTime} onSlidingComplete={this._sliderChange} />
          </View>
          <View style={{ flex: 2, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={styles.TimeTxt}>{this.formatMediaTime(this.state.duration)}</Text>
          </View>
        </View>

        <View style={{ flex: 3, flexDirection: 'row', alignContent: 'space-between' }}>
          <TouchableOpacity style={styles.btn2} onPress={this._toTheBehind}>
            <Entypo name={"controller-jump-to-start"} size={40} color={"white"} />
          </TouchableOpacity>

          <TouchableOpacity style={styles.btn1} onPress={this._play}>
            <Entypo name={this.state.paused ? "controller-play" : "controller-paus"} size={40} color={"white"} />
          </TouchableOpacity>
          <TouchableOpacity style={styles.btn2}>
            <Entypo name={"controller-next"} onPress={this._toTheNext} size={40} color={"white"} />
          </TouchableOpacity>
        </View>

      </View>
    )
  }
}
const styles = StyleSheet.create({
  disc: { width: 300, height: 300, borderRadius: 200 },
  btn1: { width: 70, height: 70, borderRadius: 45, borderColor: 'white', borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  btn2: { width: 70, height: 70, borderRadius: 45, justifyContent: 'center', alignItems: 'center' },
  TimeTxt: { fontSize: 10, color: 'white' }
})